from extensions import db
from services.constants import HOTSPOTS_TABLE_BASE_FIELDS
from services.constants import PLATFORM_CONFIG


def _extract_hotspot_db_fields(data: dict) -> dict:
    """
    提取热点数据的基础数据库字段

    Parameters:
        data: 原始数据字典

    Returns:
        提取后的数据字典
    """
    new_data = {}
    for filed in HOTSPOTS_TABLE_BASE_FIELDS:
        if filed in data:
            new_data[filed] = data[filed]
    new_data["extra_content"] = {}
    for filed in data:
        if filed not in HOTSPOTS_TABLE_BASE_FIELDS:
            new_data["extra_content"][filed] = data[filed]
    return new_data


def prepare_hotspot_data(
    hot_list: list, platform: str, section: str, crawl_at: int
) -> dict:
    """对热点数据进行预处理

    Parameters:
        hot_list: 原始的热点数据列表
        platform: 平台名称
        section: 板块名称
        crawl_at: 抓取时间戳

    Returns:
        预处理后的数据列表，可直接进行数据库批量插入
    """
    result = []
    for item in hot_list:
        data = _extract_hotspot_db_fields(item)
        data["platform"] = PLATFORM_CONFIG[platform]["id"]
        data["section"] = PLATFORM_CONFIG[platform]["sections"][section]
        data["crawl_at"] = crawl_at
        result.append(data)

    return result

def format_paginated_result(paginate) -> dict:
    """格式化分页结果
    Parameters:
        paginate: SQLAlchemy分页对象
        
    Returns:
        dict: 格式化后的分页结果
    """
    return {
        "pages": paginate.pages,
        "page": paginate.page,
        "per_page": paginate.per_page,
        "items": paginate.items,
        "total": paginate.total
    }